package com.yict.csms.resourceplan.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yict.common.entity.PageEntity;
import com.yict.common.service.impl.BaseServiceImpl;
import com.yict.csms.resourceplan.dao.IBoxContractorDao;
import com.yict.csms.resourceplan.dao.IBoxContractorLineDao;
import com.yict.csms.resourceplan.entity.BoxContractor;
import com.yict.csms.resourceplan.entity.BoxContractorLine;
import com.yict.csms.resourceplan.service.IBoxContractorService;
import com.yict.csms.system.entity.DataDict;
import com.yict.csms.system.entity.User;
import com.yict.csms.system.service.ICostService;
import com.yict.csms.system.service.IDataDictService;
import com.yict.csms.system.util.DictionaryUtils;

@Service("boxContractorService")
public class BoxContractorServiceImpl extends BaseServiceImpl<BoxContractor, Long, IBoxContractorDao> implements IBoxContractorService {
	
	@Resource(name = "boxContractorDao")
	private IBoxContractorDao boxContractorDao;
	
	@Resource(name = "boxContractorLineDao")
	private IBoxContractorLineDao boxContractorLineDao;
	
	@Resource(name = "dataDictService")
	private IDataDictService dataDictService;
	
	@Resource(name = "costService")
	private ICostService costService;
	
	public List<BoxContractor> search(Map<String, Object> queryMap, PageEntity page) {
		List<BoxContractor> list = new ArrayList<BoxContractor>();
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuilder hql = new StringBuilder("from BoxContractor t where 1=1 ");
		String fromDate = (String) queryMap.get("fromDate");
		String toDate = (String) queryMap.get("toDate");
		if (fromDate != null && fromDate.length() > 0) {
			map.put("fromDate", fromDate);
			hql.append(" and t.inputDate >= to_date(:fromDate,'yyyy-mm-dd')");
		}
		if(toDate != null && toDate.length() > 0) {
			map.put("toDate", toDate);
			hql.append(" and t.inputDate <= to_date(:toDate, 'yyyy-mm-dd')");
		}
		String shipCompanyCode = (String) queryMap.get("shipCompanyCode");
		if (shipCompanyCode != null && shipCompanyCode.length() > 0) {
			map.put("shipCompanyCode", shipCompanyCode);
			hql.append(" and t.shipCompanyCode.dictid = :shipCompanyCode");
		}
		String workNo = (String) queryMap.get("workNo");
		if (workNo != null && workNo.length() > 0) {
			map.put("workNo", workNo);
			hql.append(" and t.workNo like :workNo");
		}
		Long profeId = (Long) queryMap.get("profeId");
		if (profeId != null) {
			map.put("profeId", profeId);
			hql.append(" and t.profeId.profeid in (:profeId)");
		}
		String status = (String) queryMap.get("statusCode");
		if (status != null && status.length() > 0) {
			map.put("status", status);
			hql.append(" and t.status.dictid = :status");
		}
		Long companyId = (Long)queryMap.get("companyId");
		if (companyId != null) {
			map.put("companyId", companyId);
			hql.append(" and t.companyId.companyId in (:companyId)");
		}
		
		int count = this.getBaseDao().queryCount(
				"select count(*) " + hql.toString(), map);
		if(page == null) {
			page = new PageEntity();
		}
		page.setTotalRecord(count);
		if (count > 0) {
			StringBuilder orderString = new StringBuilder("");
			if (page.getField() != null&&!"".equals(page.getField()) &&page.getOrder()!= null && !"".equals(page.getOrder())) {
				if(page.getField().equals("shipCompanyName")) {
					orderString.append("shipCompanyCode " + page.getOrder());
				} else if (page.getField().equals("profeName")){
					orderString.append("profeId " + page.getOrder());
				} else if (page.getField().equals("companySName")){
					orderString.append("companyId " + page.getOrder());
				} else if (page.getField().equals("assignedPersonName")){
					orderString.append("assignedPerson " + page.getOrder());
				} else if (page.getField().equals("orderPersonName")){
					orderString.append("orderPerson " + page.getOrder());
				} else if (page.getField().equals("statusName")){
					orderString.append("status " + page.getOrder());
				} else {
					orderString.append(page.getField() + page.getOrder());
				}
				hql.append(" order by ").append(orderString);
			} else {
				hql.append(" order by t.workNo");
			}
			
			list = this.getBaseDao().list(hql.toString(), map,
					(page.getToPage() - 1) * page.getPageSize(),
					page.getPageSize());
		}
		return list;
	}
	
	@Override
	public List<BoxContractorLine> search(String workNo) {
		Long bcId = 0L;
		try {
			
			bcId = boxContractorDao.fingByWorkNo(workNo).getBcId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return boxContractorLineDao.searchByBcId(bcId);
	}

	@Resource(name = "boxContractorDao")
	public void setBaseDao(IBoxContractorDao baseDao) {
		super.setBaseDao(baseDao);
	}
	
	@Transactional(readOnly = false)
	@Override
	public boolean update(BoxContractorLine boxContractorLine) throws Exception {
		return boxContractorLineDao.update(boxContractorLine);
	}

	@Transactional(readOnly = false)
	@Override
	public boolean update(BoxContractor boxContractor,
			List<BoxContractorLine> boxContractorLines) throws Exception {
		boxContractorDao.update(boxContractor);
		for (BoxContractorLine boxContractorLine : boxContractorLines) {
			boxContractorLineDao.update(boxContractorLine);
		}
		return true;
	}

	@Transactional(readOnly = false)
	@Override
	public boolean backAssigned(List<Long> bcId) {
		return boxContractorLineDao.backAssigned(bcId);
	}

	@Transactional(readOnly = false)
	@Override
	public boolean commit(BoxContractor boxContractor, List<BoxContractorLine> boxContractorLines) throws Exception {
		boolean flag = false;
		boxContractorDao.update(boxContractor);
		for (BoxContractorLine boxContractorLine : boxContractorLines) {
			if(boxContractorLine.getIsDelete() != null && boxContractorLine.getIsDelete().equals("Y")) {
				boxContractorLineDao.remove(boxContractorLine);
			} else {
				boxContractorLineDao.update(boxContractorLine);
			}
		}
		flag = true;
		return flag;
	}

	@Transactional(readOnly = false)
	@Override
	public boolean commitAll(List<BoxContractor> boxContractorLines) throws Exception {
		boolean flag = false;
		Long[] bcIds = new Long[boxContractorLines.size()];
		int i = 0;
		for (BoxContractor boxContractor : boxContractorLines) {
			boxContractorDao.update(boxContractor);
			bcIds[i] = boxContractor.getBcId();
			i++;
		}
		flag = boxContractorLineDao.removeY(bcIds);
		return flag;
	}

	@Override
	public List<BoxContractorLine> searchByBcId(Long bcId) {
		return boxContractorLineDao.searchByBcId(bcId, "Y");
	}

	@Transactional(readOnly = false,rollbackFor={Exception.class})
	@Override
	public boolean commitAll(List<Long> bcIds, DataDict status, User us,
			Date date) throws Exception {
		boolean bool = false;
		bool = boxContractorDao.commitAll(bcIds, status, us, date);
		DataDict dataDict2 = new DataDict();
		dataDict2 = dataDictService.findByCode(DictionaryUtils.DICT_CODE_COST_SOURCE_4);
		for (Long id : bcIds) {
			BoxContractor boxContractor = boxContractorDao.findbyId(id);
			//生成计费记录
			bool = costService.createCost(boxContractor.getCompanyId().getCompanyId(), boxContractor.getProfeId().getProfeid(), null, id, null, boxContractor.getInputDate(), 
					null, null, null, null, null, new BigDecimal(boxContractor.getQuantity()), dataDict2.getDictid(), us);
		}
		return bool;
	}

	@Transactional(readOnly = false)
	@Override
	public boolean backAssigned(List<Long> bcId, DataDict status, User us, Date date) {
		return boxContractorDao.backAssigned(bcId, status, us, date);
	}
	
	@Override
	public boolean backAssigned(Long bcId, User us) {
		DataDict dict = dataDictService.findByCode(DictionaryUtils.BOX_STATUS_2);
		return boxContractorDao.backAssigned(bcId, dict, us);
	}

	@Override
	public boolean check(Long bcId, boolean isPC) {
		List<BoxContractorLine> list = new ArrayList<BoxContractorLine>();
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuilder hql = new StringBuilder("from BoxContractorLine t where 1=1 and t.bcId in (:bcId) and ( t.tcOrtx is null or " +
				" t.ccOrcx is null or t.pcTurnOn is null or t.pcCutOff is null )");
		map.put("bcId", bcId);
		
		if(!isPC) {
			hql.append("or t.ptiTurnOn is null or t.ptiCutOff is null ");
		}
		
		list = boxContractorLineDao.list(hql.toString(), map, 0, 0);
		if(list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

}
